<?php
/**
 * wechat php test
 */

//define your token
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
//$wechatObj->valid();//接口验证
$wechatObj->responseMsg();//调用回复消息方法
class wechatCallbackapiTest
{
    public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        //extract post data
        if (!empty($postStr)){
            /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
               the best way is to check the validity of xml by yourself */
            libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $keyword = trim($postObj->Content);
            $time = time();
            $msgType = $postObj->MsgType;//消息类型
            $event = $postObj->Event;//时间类型，subscribe（订阅）、unsubscribe（取消订阅）
            $textTpl = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            <FuncFlag>0</FuncFlag>
                            </xml>";

            switch($msgType){
                case "event":
                    if($event=="subscribe"){
                        $contentStr = "Hi,欢迎关注海仙日用百货!"."\n"."回复数字'1',了解店铺地址."."\n"."回复数字'2',了解商品种类.";
                    }
                    break;
                case "image":
                    if($event=="subscribe"){
                        $contentStr = "Hi,欢迎关注海仙日用百货!"."\n"."回复数字'1',了解店铺地址."."\n"."回复数字'2',了解商品种类.";
                    }
                    break;
                case "text":
//                    switch($keyword){
//                        case "1":
//                            $contentStr = "店铺地址："."\n"."杭州市江干艮山西路233号新东升市场地下室第一排.";
//                            break;
//                        case "2":
//                            $contentStr = "商品种类:"."\n"."杯子、碗、棉签、水桶、垃圾桶、洗碗巾(刷)、拖把、扫把、"
//                                ."衣架、粘钩、牙签、垃圾袋、保鲜袋(膜)、剪刀、水果刀、饭盒等.";
//                            break;
//                        default:
//                            $contentStr = "对不起,你的内容我会稍后回复";
//                    }
                    if($keyword){

                        header("Content-Type: text/html;charset=utf-8");
                        $contentStr="";
                        $wd = $keyword;

//搜腾讯vip
                        $unwd =  urlencode($wd);

//搜在线
                        $ddd = file_get_contents("http://v.sigu.me/search.php?wd=$wd");

                        $result1 = preg_match_all('/<span class="s_tit">(.*?)<span class="s_type">/', $ddd, $name);

                        foreach($name[0] as $vv){

                            preg_match_all('/".*?"/', $vv, $aa);
                            preg_match('/<strong>.*<\/strong>/', $vv, $bb);

                            $uu = urlencode('v.sigu.me/'.$aa[0][1]);

                            $book = array("a"=>$uu);
                            $json= urldecode(json_encode($book['a']));
                            $json=explode('"',$json);
                            $bb[0] = ltrim($bb[0],'<strong>');
                            $bb[0] = rtrim($bb[0],'</strong>');

                            $url=json_decode(file_get_contents('http://api.t.sina.com.cn/short_url/shorten.json?source=3271760578&url_long=http://v.sigu.me/'.$json[2]),true);
                            $url_short = $url[0]['url_short'];

                            //echo '【在线】'.$bb[0];echo "<br>";echo $url_short;echo "<br>";
                            $contentStr .="$bb[0],$url_short \n";
                        }
//搜网盘




                        $url=json_decode(file_get_contents("http://api.t.sina.com.cn/short_url/shorten.json?source=3271760578&url_long=http://www.repanso.com/q?wd=$unwd"),true);
//var_dump($url);exit;
                        $url_short = $url[0]['url_short'];
                        //$contentStr = '【网盘】'.$wd;echo "<br>";echo $url_short;echo "<br>";
                        $contentStr .="\n $wd,$url_short";

//                        $xcs = file_get_contents("http://api.sc2h.cn/api/94api.php?type=xzs&msg=");
//
//                        $contentStr .="\n 推荐小常识：$xcs";
                       // $img = file_get_contents("http://api.sc2h.cn/api/maid.php?data=2&sign=user&msg=1");
                        $contentStr .="<image>https://t11.baidu.com/it/u=998228302,3043429389&fm=76</image>";
                        #$contentStr .="[imgurl]https://t11.baidu.com/it/u=998228302,3043429389&fm=76[/imgurl]";
//if($tx_url_short){
//echo "PS:腾讯vip视频只破解最新两集，想看更多输入指令搜腾讯+剧名。";echo "<br>";
//}
//echo "PS省钱绝招:新增优惠券查询功能。购物之前先过来找小汁查一下是否有隐藏的优惠券吧。教程地址：http://t.cn/RBola9B";echo "<br>";
                      //  echo "PS温馨提示:公众号资源更多不失效。更多电影小说资源关注微信公众号 【微博热点排行】传送门：http://t.cn/RkHVMyX";
                    }
                    break;
            }
            $msgType = "text";
            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
            echo $resultStr;
        }else {
            echo "";
            exit;
        }
    }

    private function checkSignature()
    {
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }

        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
}


?>

